var express = require('express');
var router = express.Router();
var mongdb = require('mongodb');
var MongoClient = require('mongodb').MongoClient
var config = require('../config/db')    //加载数据库配置模块
var bcrypt = require('bcryptjs');     //导入加密模块
const formidable = require('formidable');
const path = require('path')
const jwt = require('jsonwebtoken')
var passport = require('passport')

/*登录验证*/
router.post('/login', async function (req, res, next) {
  let { userName, userPwd } = req.body                       //获取登录用户的用户名和密码
  let client = await MongoClient.connect(config.url)      //获取数据库连接对象
  let db = client.db()
  users = await db.collection('users').find({ 'name': userName }).toArray()    //获取和登录用户名相同的用户数据
  //判断是否存在匹配，并且密码验证正确的用户数据
  if (users.length > 0 && bcrypt.compareSync(userPwd, users[0].password)) {
    jwt.sign(users[0],'mykey',{expiresIn:60*60},(err,token)=>{
      console.log('mytoken:',token);
       if(err){
        res.json({ code: 200, message: 'error'+err.message });
       }else{
        let user = 'Bearer '+  token
        console.log('user:',user);
        res.json({ code: 200, message: 'ok', user,data:users[0]}); 
       }
    })
  } else {
    res.json({ code: 200, message: 'error' });
  }
});


/*普通注册*/
router.post('/register', async function (req, res, next) {
  let { userName, userPwd } = req.body                       //获取注册用户的用户名和密码
  let client = await MongoClient.connect(config.url)      //获取数据库连接对象
  let db = client.db()
  let salt = bcrypt.genSaltSync(10);                      //加盐
  let hash = bcrypt.hashSync(userPwd, salt);            //加密
  //创建新用户对象
  let registerUser = {
    "name": userName,
    "password": hash,
    "sex": true,
    "mobile": "",
    "address": null,
    "birth": null,
    "headpic": "headpic.jpg"
  }
  let users = await db.collection('users').find({ 'name': userName }).toArray()
  console.log(users);
  if(users.length>0){
    res.json({ code: 200, message: '用户名重复' });
  }else{
    let results = await db.collection('users').insertOne(registerUser) //执行添加用户的操作
    console.log('results:', results)
    //判断用户是否添加成功
    if (results.acknowledged) {
      res.json({ code: 200, message: 'ok' });
    } else {
      res.json({ code: 200, message: 'error' });
    }
  }
});


/*获取当前登录用户的基本信息*/
router.get('/getUserInfoById', async function (req, res, next) {
  let { userId } = req.query                       //获取当前登录用户的用户ID
  let client = await MongoClient.connect(config.url)      //获取数据库连接对象
  let db = client.db()
  users = await db.collection('users').find({ '_id': new mongdb.ObjectId(userId) }).toArray()    //获取和登录用户id相同的用户数据,注意字符串id必须转换成ObjectId类型
  //判断是否存在匹配的用户数据
  if (users.length > 0) {
    res.json({ code: 200, message: 'ok', user: users[0] });   //返回登录成功的信息，并返回当前登录用户数据，给前端使用
  } else {
    res.json({ code: 200, message: 'error' });
  }
});

/*上传头像*/
router.post('/uploadHeadPic', passport.authenticate('jwt', { session: false }), function (req, res, next) { 
  var dirPath = path.join(__dirname, '..', 'public', 'upload')        //设置上传文件保存的位置
  // parse a file upload
  const form = formidable({ multiples: true, uploadDir: dirPath, keepExtensions: true });
  //接受上传的文件和字段，并执行后续的处理
  form.parse(req, async function (err, fields, files) {
    if (err) {
      res.json({ code: 200, message: '上传失败' })
      return;
    }
    let headpic = files.file.newFilename    //获取上传文件的新名称
    let userId = req.user._id
    let client = await MongoClient.connect(config.url)      //获取数据库连接对象
    let db = client.db()
    await db.collection('users').updateOne({ '_id': new mongdb.ObjectId(userId) }, { $set: { headpic } })
    res.json({ code: 200, message: 'ok', data: headpic})
  });
})

/*修改密码*/
router.post('/changePwd',  passport.authenticate('jwt', { session: false }),async function (req, res, next) {
  let { userOldPwd ,userNewPwd } = req.body      // 获取当前用户的新旧密码
  let client = await MongoClient.connect(config.url)      //获取数据库连接对象
  let db = client.db()
  let localPwd = await db.collection('users').find({  '_id': new mongdb.ObjectId(req.user._id) }).toArray()
  console.log('localPwd',localPwd)
  console.log('jiu',userOldPwd)
  console.log("xin",userNewPwd)
  //判断当前用户的密码和输入原密码是否相同
  if (bcrypt.compareSync(userOldPwd, req.user.password)) {
    let salt = bcrypt.genSaltSync(10);                      //加盐
    let hash = bcrypt.hashSync(userNewPwd, salt);            //把新密码加密
    //更新旧密码
    let results = await db.collection('users').updateOne({ '_id': new mongdb.ObjectId(req.user._id) }, { $set: { password: hash } })
    res.json({ code: 200, message: 'ok' });
  } else {
    res.json({ code: 200, message: '旧密码不正确！' });
  }
});

/*修改名字*/
router.post('/changeName',  passport.authenticate('jwt', { session: false }),async function (req, res, next) {
  let {userId,newname} = req.body 
  console.log(req.body );   // 获取当前用户的id
  let client = await MongoClient.connect(config.url)      //获取数据库连接对象
  let db = client.db()
  users = await db.collection('users').find({ '_id': new mongdb.ObjectId(userId) }).toArray() //获取和当前用户id相同的用户数据
  if (users.length>0) {
    await db.collection('users').updateOne({ '_id': new mongdb.ObjectId(userId) }, { $set: { name:newname } })
    res.json({ code: 200, message: 'ok', user: users[0] }); 
  } else {
    res.json({ code: 200, message: 'no' });
  }
});
module.exports = router;